<script setup>
import { useForm } from '@/components'

defineOptions({
  name: 'DynamicForm'
})

const $props = defineProps({
  schema: { type: Object, required: true },
  formdata: { type: Object },
  submit: { type: Function, required: true },
  loading: { type: Boolean, defaultValue: false },
  submitProp: { type: Object, defaultValue: {} }
})

const { handleSubmit } = useForm()
const onSubmit = handleSubmit((values) => {
  $props.submit(values)
})
</script>
<template>
  <form @submit="onSubmit($event)">
    <div
      class="flex gap-3 justify-content-end align-content-center"
      v-for="{ as, name, label, children, required = false, ...attrs } in $props.schema.fields"
      :key="name"
    >
      <label v-if="label" class="font-medium text-lg text-justify pt-2" :for="name"
        ><span v-if="required" class="text-red-500">*</span> {{ label }}</label
      >
      <section class="flex flex-column w-100">
        <Field
          :disabled="$props.loading"
          :as="as"
          :id="name"
          :name="name"
          v-bind="attrs"
          v-model="$props.formdata[name]"
        >
          <template v-if="children && children.length">
            <component
              v-for="({ tag, text, ...childAttrs }, idx) in children"
              :key="idx"
              :is="tag"
              v-bind="childAttrs"
            >
              {{ text }}
            </component>
          </template>
        </Field>
        <small> <ErrorMessage :name="name" class="text-red-500" />&nbsp; </small>
      </section>
    </div>
    <Button
      size="large"
      type="submit"
      :loading="$props.loading"
      label="Ok"
      v-bind="$props.submitProp"
    />
  </form>
</template>
